import time
import json
from utils.config import deviceid, logpath, appkey, secret, gps_postIntervalTime, height_offset, speed_thresh, \
    result_path
from tendo.singleton import SingleInstance
from os.path import isdir
from os import mkdir
from utils.logger import Logger
from utils.tools import utcToBj

gps_logger = Logger(filename=f'{logpath}/road_gps.log').logger
gps_logger.info("road_gps start!")

try:
    Single = SingleInstance()
except:
    gps_logger.error('road gps process already  exist! ')
    exit()


def gpsSever(dict):
    cnt_lowspeed = 0
    gps_init_time = int(time.time())
    isstart = 1
    filter = False

    _gdata = ''
    lat0, lon0 = 0, 0

    while True:
        # time.sleep(0.1)
        if int(time.time()) - gps_init_time >= gps_postIntervalTime:
            gps_init_time = int(time.time())
            # gpsdata = "$GPGGA,032857.00,3040.75305015,N,12100.70562049,E,4,34,0.6,4.8589,M,10.4975,M,02,926*54"
            if len(dict) < 2:
                gps_logger.error("gps data is uninitialized!")
                continue
            gpsdata = dict[0]
            speed = dict[1]
            if gpsdata is None or speed is None:
                gps_logger.error("gps data is None or speed is None!")
                continue
            if _gdata == gpsdata:
                gps_logger.error("gps data is same!")
                continue
            _gdata = gpsdata

            if speed < speed_thresh:
                cnt_lowspeed += 1
            else:
                cnt_lowspeed = 0
            if cnt_lowspeed >= 3:
                gps_logger.warning('low speed')
                continue

            # skip gps data with long distance
            gpsdata = gpsdata.strip()
            lat = float(gpsdata.split(',')[2].strip())
            lon = float(gpsdata.split(',')[4].strip())
            laln = abs(lat - lat0) + abs(lon - lon0)  # 两点间经纬度距离
            lat0, lon0 = lat, lon
            if filter and laln > 0.1:  # 0.1min = 200m
                filter = False
                continue

            gps_logger.info(f"GPS: {gpsdata} isstart:{isstart}")

            utime = gpsdata.split(",")[1].split('.')[0]
            ctime = utcToBj(utime)
            gpsJData = {'ctime': ctime, 'deviceid': deviceid, 'appkey': appkey, 'secret': secret, 'gngga': gpsdata,
                        'speed': speed, 'height_offset': height_offset, 'isstart': isstart}

            gpsSaveDir = f"{result_path}/gps/"
            if not isdir(gpsSaveDir):
                mkdir(gpsSaveDir)

            ftime = time.strftime("%Y%m%d%H%M%S", time.localtime())
            with open(f'{gpsSaveDir}/{ftime}.json', 'w') as f:
                strGpsData = json.dumps(gpsJData)
                leng = f.write(strGpsData)
                if leng == len(strGpsData):
                    isstart = 0
            filter = True


if __name__ == '__main__':
    dict = {0: "$GPGGA,032857.00,3040.75305015,N,12100.70562049,E,4,34,0.6,4.8589,M,10.4975,M,02,926*54", 1: 8.2}
    gpsSever(dict)
